<template>
  <div class="login">
    <el-form
      :model="form"
      label-width="auto"
      class="login_form"
      :rules="rules"
      ref="loginForm"
    >
      <el-form-item class="login_form_label" prop="username">
        <el-input
          v-model="form.username"
          prefix-icon="User"
          placeholder="请输入用户名"
        />
      </el-form-item>
      <el-form-item class="login_form_label" prop="password">
        <el-input
          v-model="form.password"
          prefix-icon="Lock"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
      <el-form-item class="login_form_item">
        <el-button
          type="primary"
          class="login_form_btn"
          @click="login"
          :loading="loading"
        >
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useUserStore } from '@/stores/modules/user'
import { ElMessage, ElNotification } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import '@/styles/login/index.less'
import { getTime } from '@/utils/time'

const store = useUserStore()
const router = useRouter()
const route = useRoute()
const form = reactive({
  username: 'admin',
  password: '111111'
})
const rules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [
    {
      required: true,
      message: '密码不能为空',
      trigger: 'blur'
    }
  ]
}
// 获取 form 实例
const loginForm = ref()
let loading = ref(false)

// 登录
const login = async () => {
  await loginForm.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true
      try {
        await store.userLogin(form)
        let redirect: any = route.query.redirect
        router.push({ path: redirect || '/' })
        ElNotification({
          title: `Hi,${getTime()}`,
          message: '欢迎回来',
          type: 'success'
        })
        loading.value = false
      } catch (error: any) {
        loading.value = false
        ElMessage.error(error.message)
      }
    }
  })
}
</script>

<style scoped></style>
